3 * Local file in the wiki's own database.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileAbstraction
24 use \MediaWiki\Logger\LoggerFactory
;
25 use Wikimedia\Rdbms\IDatabase
;
28 * Class to represent a local file in the wiki's own database
30 * Provides methods to retrieve paths (physical, logical, URL),
31 * to generate image thumbnails or for uploading.
33 * Note that only the repo object knows what its file class is called. You should
34 * never name a file class explictly outside of the repo class. Instead use the
35 * repo's factory functions to generate file objects, for example:
37 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
39 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
42 * @ingroup FileAbstraction
44 class LocalFile
extends File
{
45 const VERSION
= 10; // cache version
47 const CACHE_FIELD_MAX_LEN
= 1000;
49 /** @var bool Does the file exist on disk? (loadFromXxx) */
50 protected $fileExists;
52 /** @var int Image width */
55 /** @var int Image height */
58 /** @var int Returned by getimagesize (loadFromXxx) */
61 /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */
62 protected $media_type;
64 /** @var string MIME type, determined by MimeMagic::guessMimeType */
67 /** @var int Size in bytes (loadFromXxx) */
70 /** @var string Handler-specific metadata */
73 /** @var string SHA-1 base 36 content hash */
76 /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */
77 protected $dataLoaded;
79 /** @var bool Whether or not lazy-loaded data has been loaded from the database */
80 protected $extraDataLoaded;
82 /** @var int Bitfield akin to rev_deleted */
86 protected $repoClass = 'LocalRepo';
88 /** @var int Number of line to return by nextHistoryLine() (constructor) */
91 /** @var int Result of the query for the file's history (nextHistoryLine) */
94 /** @var string Major MIME type */
97 /** @var string Minor MIME type */
100 /** @var string Upload timestamp */
103 /** @var int User ID of uploader */
106 /** @var string User name of uploader */
109 /** @var string Description of current revision of the file */
110 private $description;
112 /** @var string TS_MW timestamp of the last change of the file description */
113 private $descriptionTouched;
115 /** @var bool Whether the row was upgraded on load */
118 /** @var bool Whether the row was scheduled to upgrade on load */
121 /** @var bool True if the image row is locked */
124 /** @var bool True if the image row is locked with a lock initiated transaction */
125 private $lockedOwnTrx;
127 /** @var bool True if file is not present in file system. Not to be cached in memcached */
130 // @note: higher than IDBAccessObject constants
131 const LOAD_ALL
= 16; // integer; load all the lazy fields too (like metadata)
133 const ATOMIC_SECTION_LOCK
= 'LocalFile::lockingTransaction';
136 * Create a LocalFile from a title
137 * Do not call this except from inside a repo class.
139 * Note: $unused param is only here to avoid an E_STRICT
141 * @param Title $title
142 * @param FileRepo $repo
143 * @param null $unused
147 static function newFromTitle( $title, $repo, $unused = null ) {
148 return new self( $title, $repo );
152 * Create a LocalFile from a title
153 * Do not call this except from inside a repo class.
155 * @param stdClass $row
156 * @param FileRepo $repo
160 static function newFromRow( $row, $repo ) {
161 $title = Title
::makeTitle( NS_FILE
, $row->img_name
);
162 $file = new self( $title, $repo );
163 $file->loadFromRow( $row );
169 * Create a LocalFile from a SHA-1 key
170 * Do not call this except from inside a repo class.
172 * @param string $sha1 Base-36 SHA-1
173 * @param LocalRepo $repo
174 * @param string|bool $timestamp MW_timestamp (optional)
175 * @return bool|LocalFile
177 static function newFromKey( $sha1, $repo, $timestamp = false ) {
178 $dbr = $repo->getReplicaDB();
180 $conds = [ 'img_sha1' => $sha1 ];
182 $conds['img_timestamp'] = $dbr->timestamp( $timestamp );
185 $row = $dbr->selectRow( 'image', self
::selectFields(), $conds, __METHOD__
);
187 return self
::newFromRow( $row, $repo );
194 * Fields in the image table
197 static function selectFields() {
218 * Do not call this except from inside a repo class.
219 * @param Title $title
220 * @param FileRepo $repo
222 function __construct( $title, $repo ) {
223 parent
::__construct( $title, $repo );
225 $this->metadata
= '';
226 $this->historyLine
= 0;
227 $this->historyRes
= null;
228 $this->dataLoaded
= false;
229 $this->extraDataLoaded
= false;
231 $this->assertRepoDefined();
232 $this->assertTitleDefined();
236 * Get the memcached key for the main data for this file, or false if
237 * there is no access to the shared cache.
238 * @return string|bool
240 function getCacheKey() {
241 return $this->repo
->getSharedCacheKey( 'file', sha1( $this->getName() ) );
245 * @param WANObjectCache $cache
249 public function getMutableCacheKeys( WANObjectCache
$cache ) {
250 return [ $this->getCacheKey() ];
254 * Try to load file metadata from memcached, falling back to the database
256 private function loadFromCache() {
257 $this->dataLoaded
= false;
258 $this->extraDataLoaded
= false;
260 $key = $this->getCacheKey();
262 $this->loadFromDB( self
::READ_NORMAL
);
267 $cache = ObjectCache
::getMainWANInstance();
268 $cachedValues = $cache->getWithSetCallback(
271 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
272 $setOpts +
= Database
::getCacheSetOptions( $this->repo
->getReplicaDB() );
274 $this->loadFromDB( self
::READ_NORMAL
);
276 $fields = $this->getCacheFields( '' );
277 $cacheVal['fileExists'] = $this->fileExists
;
278 if ( $this->fileExists
) {
279 foreach ( $fields as $field ) {
280 $cacheVal[$field] = $this->$field;
283 // Strip off excessive entries from the subset of fields that can become large.
284 // If the cache value gets to large it will not fit in memcached and nothing will
285 // get cached at all, causing master queries for any file access.
286 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
287 if ( isset( $cacheVal[$field] )
288 && strlen( $cacheVal[$field] ) > 100 * 1024
290 unset( $cacheVal[$field] ); // don't let the value get too big
294 if ( $this->fileExists
) {
295 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->timestamp
), $ttl );
297 $ttl = $cache::TTL_DAY
;
302 [ 'version' => self
::VERSION
]
305 $this->fileExists
= $cachedValues['fileExists'];
306 if ( $this->fileExists
) {
307 $this->setProps( $cachedValues );
310 $this->dataLoaded
= true;
311 $this->extraDataLoaded
= true;
312 foreach ( $this->getLazyCacheFields( '' ) as $field ) {
313 $this->extraDataLoaded
= $this->extraDataLoaded
&& isset( $cachedValues[$field] );
318 * Purge the file object/metadata cache
320 public function invalidateCache() {
321 $key = $this->getCacheKey();
326 $this->repo
->getMasterDB()->onTransactionPreCommitOrIdle(
327 function () use ( $key ) {
328 ObjectCache
::getMainWANInstance()->delete( $key );
335 * Load metadata from the file itself
337 function loadFromFile() {
338 $props = $this->repo
->getFileProps( $this->getVirtualUrl() );
339 $this->setProps( $props );
343 * @param string $prefix
346 function getCacheFields( $prefix = 'img_' ) {
347 static $fields = [ 'size', 'width', 'height', 'bits', 'media_type',
348 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user',
349 'user_text', 'description' ];
350 static $results = [];
352 if ( $prefix == '' ) {
356 if ( !isset( $results[$prefix] ) ) {
357 $prefixedFields = [];
358 foreach ( $fields as $field ) {
359 $prefixedFields[] = $prefix . $field;
361 $results[$prefix] = $prefixedFields;
364 return $results[$prefix];
368 * @param string $prefix
371 function getLazyCacheFields( $prefix = 'img_' ) {
372 static $fields = [ 'metadata' ];
373 static $results = [];
375 if ( $prefix == '' ) {
379 if ( !isset( $results[$prefix] ) ) {
380 $prefixedFields = [];
381 foreach ( $fields as $field ) {
382 $prefixedFields[] = $prefix . $field;
384 $results[$prefix] = $prefixedFields;
387 return $results[$prefix];
391 * Load file metadata from the DB
394 function loadFromDB( $flags = 0 ) {
395 $fname = static::class . '::' . __FUNCTION__
;
397 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
398 $this->dataLoaded
= true;
399 $this->extraDataLoaded
= true;
401 $dbr = ( $flags & self
::READ_LATEST
)
402 ?
$this->repo
->getMasterDB()
403 : $this->repo
->getReplicaDB();
405 $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ),
406 [ 'img_name' => $this->getName() ], $fname );
409 $this->loadFromRow( $row );
411 $this->fileExists
= false;
416 * Load lazy file metadata from the DB.
417 * This covers fields that are sometimes not cached.
419 protected function loadExtraFromDB() {
420 $fname = static::class . '::' . __FUNCTION__
;
422 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
423 $this->extraDataLoaded
= true;
425 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getReplicaDB(), $fname );
427 $fieldMap = $this->loadFieldsWithTimestamp( $this->repo
->getMasterDB(), $fname );
431 foreach ( $fieldMap as $name => $value ) {
432 $this->$name = $value;
435 throw new MWException( "Could not find data for image '{$this->getName()}'." );
440 * @param IDatabase $dbr
441 * @param string $fname
444 private function loadFieldsWithTimestamp( $dbr, $fname ) {
447 $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ), [
448 'img_name' => $this->getName(),
449 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() )
452 $fieldMap = $this->unprefixRow( $row, 'img_' );
454 # File may have been uploaded over in the meantime; check the old versions
455 $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ), [
456 'oi_name' => $this->getName(),
457 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() )
460 $fieldMap = $this->unprefixRow( $row, 'oi_' );
468 * @param array|object $row
469 * @param string $prefix
470 * @throws MWException
473 protected function unprefixRow( $row, $prefix = 'img_' ) {
474 $array = (array)$row;
475 $prefixLength = strlen( $prefix );
477 // Sanity check prefix once
478 if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) {
479 throw new MWException( __METHOD__
. ': incorrect $prefix parameter' );
483 foreach ( $array as $name => $value ) {
484 $decoded[substr( $name, $prefixLength )] = $value;
491 * Decode a row from the database (either object or array) to an array
492 * with timestamps and MIME types decoded, and the field prefix removed.
494 * @param string $prefix
495 * @throws MWException
498 function decodeRow( $row, $prefix = 'img_' ) {
499 $decoded = $this->unprefixRow( $row, $prefix );
501 $decoded['timestamp'] = wfTimestamp( TS_MW
, $decoded['timestamp'] );
503 $decoded['metadata'] = $this->repo
->getReplicaDB()->decodeBlob( $decoded['metadata'] );
505 if ( empty( $decoded['major_mime'] ) ) {
506 $decoded['mime'] = 'unknown/unknown';
508 if ( !$decoded['minor_mime'] ) {
509 $decoded['minor_mime'] = 'unknown';
511 $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime'];
514 // Trim zero padding from char/binary field
515 $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" );
517 // Normalize some fields to integer type, per their database definition.
518 // Use unary + so that overflows will be upgraded to double instead of
519 // being trucated as with intval(). This is important to allow >2GB
520 // files on 32-bit systems.
521 foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) {
522 $decoded[$field] = +
$decoded[$field];
529 * Load file metadata from a DB result row
532 * @param string $prefix
534 function loadFromRow( $row, $prefix = 'img_' ) {
535 $this->dataLoaded
= true;
536 $this->extraDataLoaded
= true;
538 $array = $this->decodeRow( $row, $prefix );
540 foreach ( $array as $name => $value ) {
541 $this->$name = $value;
544 $this->fileExists
= true;
545 $this->maybeUpgradeRow();
549 * Load file metadata from cache or DB, unless already loaded
552 function load( $flags = 0 ) {
553 if ( !$this->dataLoaded
) {
554 if ( $flags & self
::READ_LATEST
) {
555 $this->loadFromDB( $flags );
557 $this->loadFromCache();
561 if ( ( $flags & self
::LOAD_ALL
) && !$this->extraDataLoaded
) {
562 // @note: loads on name/timestamp to reduce race condition problems
563 $this->loadExtraFromDB();
568 * Upgrade a row if it needs it
570 function maybeUpgradeRow() {
571 global $wgUpdateCompatibleMetadata;
573 if ( wfReadOnly() ||
$this->upgrading
) {
578 if ( is_null( $this->media_type
) ||
$this->mime
== 'image/svg' ) {
581 $handler = $this->getHandler();
583 $validity = $handler->isMetadataValid( $this, $this->getMetadata() );
584 if ( $validity === MediaHandler
::METADATA_BAD
) {
586 } elseif ( $validity === MediaHandler
::METADATA_COMPATIBLE
) {
587 $upgrade = $wgUpdateCompatibleMetadata;
593 $this->upgrading
= true;
594 // Defer updates unless in auto-commit CLI mode
595 DeferredUpdates
::addCallableUpdate( function() {
596 $this->upgrading
= false; // avoid duplicate updates
599 } catch ( LocalFileLockError
$e ) {
600 // let the other process handle it (or do it next time)
607 * @return bool Whether upgradeRow() ran for this object
609 function getUpgraded() {
610 return $this->upgraded
;
614 * Fix assorted version-related problems with the image row by reloading it from the file
616 function upgradeRow() {
617 $this->lock(); // begin
619 $this->loadFromFile();
621 # Don't destroy file info of missing files
622 if ( !$this->fileExists
) {
624 wfDebug( __METHOD__
. ": file does not exist, aborting\n" );
629 $dbw = $this->repo
->getMasterDB();
630 list( $major, $minor ) = self
::splitMime( $this->mime
);
632 if ( wfReadOnly() ) {
637 wfDebug( __METHOD__
. ': upgrading ' . $this->getName() . " to the current schema\n" );
639 $dbw->update( 'image',
641 'img_size' => $this->size
, // sanity
642 'img_width' => $this->width
,
643 'img_height' => $this->height
,
644 'img_bits' => $this->bits
,
645 'img_media_type' => $this->media_type
,
646 'img_major_mime' => $major,
647 'img_minor_mime' => $minor,
648 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
649 'img_sha1' => $this->sha1
,
651 [ 'img_name' => $this->getName() ],
655 $this->invalidateCache();
657 $this->unlock(); // done
658 $this->upgraded
= true; // avoid rework/retries
662 * Set properties in this object to be equal to those given in the
663 * associative array $info. Only cacheable fields can be set.
664 * All fields *must* be set in $info except for getLazyCacheFields().
666 * If 'mime' is given, it will be split into major_mime/minor_mime.
667 * If major_mime/minor_mime are given, $this->mime will also be set.
671 function setProps( $info ) {
672 $this->dataLoaded
= true;
673 $fields = $this->getCacheFields( '' );
674 $fields[] = 'fileExists';
676 foreach ( $fields as $field ) {
677 if ( isset( $info[$field] ) ) {
678 $this->$field = $info[$field];
682 // Fix up mime fields
683 if ( isset( $info['major_mime'] ) ) {
684 $this->mime
= "{$info['major_mime']}/{$info['minor_mime']}";
685 } elseif ( isset( $info['mime'] ) ) {
686 $this->mime
= $info['mime'];
687 list( $this->major_mime
, $this->minor_mime
) = self
::splitMime( $this->mime
);
691 /** splitMime inherited */
692 /** getName inherited */
693 /** getTitle inherited */
694 /** getURL inherited */
695 /** getViewURL inherited */
696 /** getPath inherited */
697 /** isVisible inherited */
702 function isMissing() {
703 if ( $this->missing
=== null ) {
704 list( $fileExists ) = $this->repo
->fileExists( $this->getVirtualUrl() );
705 $this->missing
= !$fileExists;
708 return $this->missing
;
712 * Return the width of the image
717 public function getWidth( $page = 1 ) {
720 if ( $this->isMultipage() ) {
721 $handler = $this->getHandler();
725 $dim = $handler->getPageDimensions( $this, $page );
727 return $dim['width'];
729 // For non-paged media, the false goes through an
730 // intval, turning failure into 0, so do same here.
739 * Return the height of the image
744 public function getHeight( $page = 1 ) {
747 if ( $this->isMultipage() ) {
748 $handler = $this->getHandler();
752 $dim = $handler->getPageDimensions( $this, $page );
754 return $dim['height'];
756 // For non-paged media, the false goes through an
757 // intval, turning failure into 0, so do same here.
761 return $this->height
;
766 * Returns ID or name of user who uploaded the file
768 * @param string $type 'text' or 'id'
771 function getUser( $type = 'text' ) {
774 if ( $type == 'text' ) {
775 return $this->user_text
;
777 return (int)$this->user
;
782 * Get short description URL for a file based on the page ID.
784 * @return string|null
785 * @throws MWException
788 public function getDescriptionShortUrl() {
789 $pageId = $this->title
->getArticleID();
791 if ( $pageId !== null ) {
792 $url = $this->repo
->makeUrl( [ 'curid' => $pageId ] );
793 if ( $url !== false ) {
801 * Get handler-specific metadata
804 function getMetadata() {
805 $this->load( self
::LOAD_ALL
); // large metadata is loaded in another step
806 return $this->metadata
;
812 function getBitDepth() {
815 return (int)$this->bits
;
819 * Returns the size of the image file, in bytes
822 public function getSize() {
829 * Returns the MIME type of the file.
832 function getMimeType() {
839 * Returns the type of the media in the file.
840 * Use the value returned by this function with the MEDIATYPE_xxx constants.
843 function getMediaType() {
846 return $this->media_type
;
849 /** canRender inherited */
850 /** mustRender inherited */
851 /** allowInlineDisplay inherited */
852 /** isSafeFile inherited */
853 /** isTrustedFile inherited */
856 * Returns true if the file exists on disk.
857 * @return bool Whether file exist on disk.
859 public function exists() {
862 return $this->fileExists
;
865 /** getTransformScript inherited */
866 /** getUnscaledThumb inherited */
867 /** thumbName inherited */
868 /** createThumb inherited */
869 /** transform inherited */
871 /** getHandler inherited */
872 /** iconThumb inherited */
873 /** getLastError inherited */
876 * Get all thumbnail names previously generated for this file
877 * @param string|bool $archiveName Name of an archive file, default false
878 * @return array First element is the base dir, then files in that base dir.
880 function getThumbnails( $archiveName = false ) {
881 if ( $archiveName ) {
882 $dir = $this->getArchiveThumbPath( $archiveName );
884 $dir = $this->getThumbPath();
887 $backend = $this->repo
->getBackend();
890 $iterator = $backend->getFileList( [ 'dir' => $dir ] );
891 foreach ( $iterator as $file ) {
894 } catch ( FileBackendError
$e ) {
895 } // suppress (T56674)
901 * Refresh metadata in memcached, but don't touch thumbnails or CDN
903 function purgeMetadataCache() {
904 $this->invalidateCache();
908 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN.
910 * @param array $options An array potentially with the key forThumbRefresh.
912 * @note This used to purge old thumbnails by default as well, but doesn't anymore.
914 function purgeCache( $options = [] ) {
915 // Refresh metadata cache
916 $this->purgeMetadataCache();
919 $this->purgeThumbnails( $options );
921 // Purge CDN cache for this file
922 DeferredUpdates
::addUpdate(
923 new CdnCacheUpdate( [ $this->getUrl() ] ),
924 DeferredUpdates
::PRESEND
929 * Delete cached transformed files for an archived version only.
930 * @param string $archiveName Name of the archived file
932 function purgeOldThumbnails( $archiveName ) {
933 // Get a list of old thumbnails and URLs
934 $files = $this->getThumbnails( $archiveName );
936 // Purge any custom thumbnail caches
937 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] );
940 $dir = array_shift( $files );
941 $this->purgeThumbList( $dir, $files );
945 foreach ( $files as $file ) {
946 $urls[] = $this->getArchiveThumbUrl( $archiveName, $file );
948 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
952 * Delete cached transformed files for the current version only.
953 * @param array $options
955 public function purgeThumbnails( $options = [] ) {
956 $files = $this->getThumbnails();
957 // Always purge all files from CDN regardless of handler filters
959 foreach ( $files as $file ) {
960 $urls[] = $this->getThumbUrl( $file );
962 array_shift( $urls ); // don't purge directory
964 // Give media handler a chance to filter the file purge list
965 if ( !empty( $options['forThumbRefresh'] ) ) {
966 $handler = $this->getHandler();
968 $handler->filterThumbnailPurgeList( $files, $options );
972 // Purge any custom thumbnail caches
973 Hooks
::run( 'LocalFilePurgeThumbnails', [ $this, false ] );
976 $dir = array_shift( $files );
977 $this->purgeThumbList( $dir, $files );
980 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates
::PRESEND
);
984 * Prerenders a configurable set of thumbnails
988 public function prerenderThumbnails() {
989 global $wgUploadThumbnailRenderMap;
993 $sizes = $wgUploadThumbnailRenderMap;
996 foreach ( $sizes as $size ) {
997 if ( $this->isVectorized() ||
$this->getWidth() > $size ) {
998 $jobs[] = new ThumbnailRenderJob(
1000 [ 'transformParams' => [ 'width' => $size ] ]
1006 JobQueueGroup
::singleton()->lazyPush( $jobs );
1011 * Delete a list of thumbnails visible at urls
1012 * @param string $dir Base dir of the files.
1013 * @param array $files Array of strings: relative filenames (to $dir)
1015 protected function purgeThumbList( $dir, $files ) {
1016 $fileListDebug = strtr(
1017 var_export( $files, true ),
1020 wfDebug( __METHOD__
. ": $fileListDebug\n" );
1023 foreach ( $files as $file ) {
1024 # Check that the base file name is part of the thumb name
1025 # This is a basic sanity check to avoid erasing unrelated directories
1026 if ( strpos( $file, $this->getName() ) !== false
1027 ||
strpos( $file, "-thumbnail" ) !== false // "short" thumb name
1029 $purgeList[] = "{$dir}/{$file}";
1033 # Delete the thumbnails
1034 $this->repo
->quickPurgeBatch( $purgeList );
1035 # Clear out the thumbnail directory if empty
1036 $this->repo
->quickCleanDir( $dir );
1039 /** purgeDescription inherited */
1040 /** purgeEverything inherited */
1043 * @param int $limit Optional: Limit to number of results
1044 * @param int $start Optional: Timestamp, start from
1045 * @param int $end Optional: Timestamp, end at
1047 * @return OldLocalFile[]
1049 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1050 $dbr = $this->repo
->getReplicaDB();
1051 $tables = [ 'oldimage' ];
1052 $fields = OldLocalFile
::selectFields();
1053 $conds = $opts = $join_conds = [];
1054 $eq = $inc ?
'=' : '';
1055 $conds[] = "oi_name = " . $dbr->addQuotes( $this->title
->getDBkey() );
1058 $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) );
1062 $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) );
1066 $opts['LIMIT'] = $limit;
1069 // Search backwards for time > x queries
1070 $order = ( !$start && $end !== null ) ?
'ASC' : 'DESC';
1071 $opts['ORDER BY'] = "oi_timestamp $order";
1072 $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ];
1074 // Avoid PHP 7.1 warning from passing $this by reference
1076 Hooks
::run( 'LocalFile::getHistory', [ &$localFile, &$tables, &$fields,
1077 &$conds, &$opts, &$join_conds ] );
1079 $res = $dbr->select( $tables, $fields, $conds, __METHOD__
, $opts, $join_conds );
1082 foreach ( $res as $row ) {
1083 $r[] = $this->repo
->newFileFromRow( $row );
1086 if ( $order == 'ASC' ) {
1087 $r = array_reverse( $r ); // make sure it ends up descending
1094 * Returns the history of this file, line by line.
1095 * starts with current version, then old versions.
1096 * uses $this->historyLine to check which line to return:
1097 * 0 return line for current version
1098 * 1 query for old versions, return first one
1099 * 2, ... return next old version from above query
1102 public function nextHistoryLine() {
1103 # Polymorphic function name to distinguish foreign and local fetches
1104 $fname = static::class . '::' . __FUNCTION__
;
1106 $dbr = $this->repo
->getReplicaDB();
1108 if ( $this->historyLine
== 0 ) { // called for the first time, return line from cur
1109 $this->historyRes
= $dbr->select( 'image',
1112 "'' AS oi_archive_name",
1116 [ 'img_name' => $this->title
->getDBkey() ],
1120 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1121 $this->historyRes
= null;
1125 } elseif ( $this->historyLine
== 1 ) {
1126 $this->historyRes
= $dbr->select( 'oldimage', '*',
1127 [ 'oi_name' => $this->title
->getDBkey() ],
1129 [ 'ORDER BY' => 'oi_timestamp DESC' ]
1132 $this->historyLine++
;
1134 return $dbr->fetchObject( $this->historyRes
);
1138 * Reset the history pointer to the first element of the history
1140 public function resetHistory() {
1141 $this->historyLine
= 0;
1143 if ( !is_null( $this->historyRes
) ) {
1144 $this->historyRes
= null;
1148 /** getHashPath inherited */
1149 /** getRel inherited */
1150 /** getUrlRel inherited */
1151 /** getArchiveRel inherited */
1152 /** getArchivePath inherited */
1153 /** getThumbPath inherited */
1154 /** getArchiveUrl inherited */
1155 /** getThumbUrl inherited */
1156 /** getArchiveVirtualUrl inherited */
1157 /** getThumbVirtualUrl inherited */
1158 /** isHashed inherited */
1161 * Upload a file and record it in the DB
1162 * @param string|FSFile $src Source storage path, virtual URL, or filesystem path
1163 * @param string $comment Upload description
1164 * @param string $pageText Text to use for the new description page,
1165 * if a new description page is created
1166 * @param int|bool $flags Flags for publish()
1167 * @param array|bool $props File properties, if known. This can be used to
1168 * reduce the upload time when uploading virtual URLs for which the file
1169 * info is already known
1170 * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the
1172 * @param User|null $user User object or null to use $wgUser
1173 * @param string[] $tags Change tags to add to the log entry and page revision.
1174 * (This doesn't check $user's permissions.)
1175 * @return Status On success, the value member contains the
1176 * archive name, or an empty string if it was a new file.
1178 function upload( $src, $comment, $pageText, $flags = 0, $props = false,
1179 $timestamp = false, $user = null, $tags = []
1183 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1184 return $this->readOnlyFatalStatus();
1187 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1189 if ( $this->repo
->isVirtualUrl( $srcPath )
1190 || FileBackend
::isStoragePath( $srcPath )
1192 $props = $this->repo
->getFileProps( $srcPath );
1194 $mwProps = new MWFileProps( MimeMagic
::singleton() );
1195 $props = $mwProps->getPropsFromPath( $srcPath, true );
1200 $handler = MediaHandler
::getHandler( $props['mime'] );
1202 $options['headers'] = $handler->getStreamHeaders( $props['metadata'] );
1204 $options['headers'] = [];
1207 // Trim spaces on user supplied text
1208 $comment = trim( $comment );
1210 // Truncate nicely or the DB will do it for us
1211 // non-nicely (dangling multi-byte chars, non-truncated version in cache).
1212 $comment = $wgContLang->truncate( $comment, 255 );
1213 $this->lock(); // begin
1214 $status = $this->publish( $src, $flags, $options );
1216 if ( $status->successCount
>= 2 ) {
1217 // There will be a copy+(one of move,copy,store).
1218 // The first succeeding does not commit us to updating the DB
1219 // since it simply copied the current version to a timestamped file name.
1220 // It is only *preferable* to avoid leaving such files orphaned.
1221 // Once the second operation goes through, then the current version was
1222 // updated and we must therefore update the DB too.
1223 $oldver = $status->value
;
1224 if ( !$this->recordUpload2( $oldver, $comment, $pageText, $props, $timestamp, $user, $tags ) ) {
1225 $status->fatal( 'filenotfound', $srcPath );
1229 $this->unlock(); // done
1235 * Record a file upload in the upload log and the image table
1236 * @param string $oldver
1237 * @param string $desc
1238 * @param string $license
1239 * @param string $copyStatus
1240 * @param string $source
1241 * @param bool $watch
1242 * @param string|bool $timestamp
1243 * @param User|null $user User object or null to use $wgUser
1246 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1247 $watch = false, $timestamp = false, User
$user = null ) {
1253 $pageText = SpecialUpload
::getInitialPageText( $desc, $license, $copyStatus, $source );
1255 if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) {
1260 $user->addWatch( $this->getTitle() );
1267 * Record a file upload in the upload log and the image table
1268 * @param string $oldver
1269 * @param string $comment
1270 * @param string $pageText
1271 * @param bool|array $props
1272 * @param string|bool $timestamp
1273 * @param null|User $user
1274 * @param string[] $tags
1277 function recordUpload2(
1278 $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = []
1280 if ( is_null( $user ) ) {
1285 $dbw = $this->repo
->getMasterDB();
1287 # Imports or such might force a certain timestamp; otherwise we generate
1288 # it and can fudge it slightly to keep (name,timestamp) unique on re-upload.
1289 if ( $timestamp === false ) {
1290 $timestamp = $dbw->timestamp();
1291 $allowTimeKludge = true;
1293 $allowTimeKludge = false;
1296 $props = $props ?
: $this->repo
->getFileProps( $this->getVirtualUrl() );
1297 $props['description'] = $comment;
1298 $props['user'] = $user->getId();
1299 $props['user_text'] = $user->getName();
1300 $props['timestamp'] = wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1301 $this->setProps( $props );
1303 # Fail now if the file isn't there
1304 if ( !$this->fileExists
) {
1305 wfDebug( __METHOD__
. ": File " . $this->getRel() . " went missing!\n" );
1310 $dbw->startAtomic( __METHOD__
);
1312 # Test to see if the row exists using INSERT IGNORE
1313 # This avoids race conditions by locking the row until the commit, and also
1314 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1315 $dbw->insert( 'image',
1317 'img_name' => $this->getName(),
1318 'img_size' => $this->size
,
1319 'img_width' => intval( $this->width
),
1320 'img_height' => intval( $this->height
),
1321 'img_bits' => $this->bits
,
1322 'img_media_type' => $this->media_type
,
1323 'img_major_mime' => $this->major_mime
,
1324 'img_minor_mime' => $this->minor_mime
,
1325 'img_timestamp' => $timestamp,
1326 'img_description' => $comment,
1327 'img_user' => $user->getId(),
1328 'img_user_text' => $user->getName(),
1329 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1330 'img_sha1' => $this->sha1
1336 $reupload = ( $dbw->affectedRows() == 0 );
1338 if ( $allowTimeKludge ) {
1339 # Use LOCK IN SHARE MODE to ignore any transaction snapshotting
1340 $ltimestamp = $dbw->selectField(
1343 [ 'img_name' => $this->getName() ],
1345 [ 'LOCK IN SHARE MODE' ]
1347 $lUnixtime = $ltimestamp ?
wfTimestamp( TS_UNIX
, $ltimestamp ) : false;
1348 # Avoid a timestamp that is not newer than the last version
1349 # TODO: the image/oldimage tables should be like page/revision with an ID field
1350 if ( $lUnixtime && wfTimestamp( TS_UNIX
, $timestamp ) <= $lUnixtime ) {
1351 sleep( 1 ); // fast enough re-uploads would go far in the future otherwise
1352 $timestamp = $dbw->timestamp( $lUnixtime +
1 );
1353 $this->timestamp
= wfTimestamp( TS_MW
, $timestamp ); // DB -> TS_MW
1357 # (T36993) Note: $oldver can be empty here, if the previous
1358 # version of the file was broken. Allow registration of the new
1359 # version to continue anyway, because that's better than having
1360 # an image that's not fixable by user operations.
1361 # Collision, this is an update of a file
1362 # Insert previous contents into oldimage
1363 $dbw->insertSelect( 'oldimage', 'image',
1365 'oi_name' => 'img_name',
1366 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1367 'oi_size' => 'img_size',
1368 'oi_width' => 'img_width',
1369 'oi_height' => 'img_height',
1370 'oi_bits' => 'img_bits',
1371 'oi_timestamp' => 'img_timestamp',
1372 'oi_description' => 'img_description',
1373 'oi_user' => 'img_user',
1374 'oi_user_text' => 'img_user_text',
1375 'oi_metadata' => 'img_metadata',
1376 'oi_media_type' => 'img_media_type',
1377 'oi_major_mime' => 'img_major_mime',
1378 'oi_minor_mime' => 'img_minor_mime',
1379 'oi_sha1' => 'img_sha1'
1381 [ 'img_name' => $this->getName() ],
1385 # Update the current image row
1386 $dbw->update( 'image',
1388 'img_size' => $this->size
,
1389 'img_width' => intval( $this->width
),
1390 'img_height' => intval( $this->height
),
1391 'img_bits' => $this->bits
,
1392 'img_media_type' => $this->media_type
,
1393 'img_major_mime' => $this->major_mime
,
1394 'img_minor_mime' => $this->minor_mime
,
1395 'img_timestamp' => $timestamp,
1396 'img_description' => $comment,
1397 'img_user' => $user->getId(),
1398 'img_user_text' => $user->getName(),
1399 'img_metadata' => $dbw->encodeBlob( $this->metadata
),
1400 'img_sha1' => $this->sha1
1402 [ 'img_name' => $this->getName() ],
1407 $descTitle = $this->getTitle();
1408 $descId = $descTitle->getArticleID();
1409 $wikiPage = new WikiFilePage( $descTitle );
1410 $wikiPage->setFile( $this );
1412 // Add the log entry...
1413 $logEntry = new ManualLogEntry( 'upload', $reupload ?
'overwrite' : 'upload' );
1414 $logEntry->setTimestamp( $this->timestamp
);
1415 $logEntry->setPerformer( $user );
1416 $logEntry->setComment( $comment );
1417 $logEntry->setTarget( $descTitle );
1418 // Allow people using the api to associate log entries with the upload.
1419 // Log has a timestamp, but sometimes different from upload timestamp.
1420 $logEntry->setParameters(
1422 'img_sha1' => $this->sha1
,
1423 'img_timestamp' => $timestamp,
1426 // Note we keep $logId around since during new image
1427 // creation, page doesn't exist yet, so log_page = 0
1428 // but we want it to point to the page we're making,
1429 // so we later modify the log entry.
1430 // For a similar reason, we avoid making an RC entry
1431 // now and wait until the page exists.
1432 $logId = $logEntry->insert();
1434 if ( $descTitle->exists() ) {
1435 // Use own context to get the action text in content language
1436 $formatter = LogFormatter
::newFromEntry( $logEntry );
1437 $formatter->setContext( RequestContext
::newExtraneousContext( $descTitle ) );
1438 $editSummary = $formatter->getPlainActionText();
1440 $nullRevision = Revision
::newNullRevision(
1447 if ( $nullRevision ) {
1448 $nullRevision->insertOn( $dbw );
1450 'NewRevisionFromEditComplete',
1451 [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ]
1453 $wikiPage->updateRevisionOn( $dbw, $nullRevision );
1454 // Associate null revision id
1455 $logEntry->setAssociatedRevId( $nullRevision->getId() );
1458 $newPageContent = null;
1460 // Make the description page and RC log entry post-commit
1461 $newPageContent = ContentHandler
::makeContent( $pageText, $descTitle );
1464 # Defer purges, page creation, and link updates in case they error out.
1465 # The most important thing is that files and the DB registry stay synced.
1466 $dbw->endAtomic( __METHOD__
);
1468 # Do some cache purges after final commit so that:
1469 # a) Changes are more likely to be seen post-purge
1470 # b) They won't cause rollback of the log publish/update above
1471 DeferredUpdates
::addUpdate(
1472 new AutoCommitUpdate(
1476 $reupload, $wikiPage, $newPageContent, $comment, $user,
1477 $logEntry, $logId, $descId, $tags
1479 # Update memcache after the commit
1480 $this->invalidateCache();
1482 $updateLogPage = false;
1483 if ( $newPageContent ) {
1484 # New file page; create the description page.
1485 # There's already a log entry, so don't make a second RC entry
1486 # CDN and file cache for the description page are purged by doEditContent.
1487 $status = $wikiPage->doEditContent(
1490 EDIT_NEW | EDIT_SUPPRESS_RC
,
1495 if ( isset( $status->value
['revision'] ) ) {
1496 /** @var $rev Revision */
1497 $rev = $status->value
['revision'];
1498 // Associate new page revision id
1499 $logEntry->setAssociatedRevId( $rev->getId() );
1501 // This relies on the resetArticleID() call in WikiPage::insertOn(),
1502 // which is triggered on $descTitle by doEditContent() above.
1503 if ( isset( $status->value
['revision'] ) ) {
1504 /** @var $rev Revision */
1505 $rev = $status->value
['revision'];
1506 $updateLogPage = $rev->getPage();
1509 # Existing file page: invalidate description page cache
1510 $wikiPage->getTitle()->invalidateCache();
1511 $wikiPage->getTitle()->purgeSquid();
1512 # Allow the new file version to be patrolled from the page footer
1513 Article
::purgePatrolFooterCache( $descId );
1516 # Update associated rev id. This should be done by $logEntry->insert() earlier,
1517 # but setAssociatedRevId() wasn't called at that point yet...
1518 $logParams = $logEntry->getParameters();
1519 $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId();
1520 $update = [ 'log_params' => LogEntryBase
::makeParamBlob( $logParams ) ];
1521 if ( $updateLogPage ) {
1522 # Also log page, in case where we just created it above
1523 $update['log_page'] = $updateLogPage;
1525 $this->getRepo()->getMasterDB()->update(
1528 [ 'log_id' => $logId ],
1531 $this->getRepo()->getMasterDB()->insert(
1534 'ls_field' => 'associated_rev_id',
1535 'ls_value' => $logEntry->getAssociatedRevId(),
1536 'ls_log_id' => $logId,
1541 # Add change tags, if any
1543 $logEntry->setTags( $tags );
1546 # Uploads can be patrolled
1547 $logEntry->setIsPatrollable( true );
1549 # Now that the log entry is up-to-date, make an RC entry.
1550 $logEntry->publish( $logId );
1552 # Run hook for other updates (typically more cache purging)
1553 Hooks
::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] );
1556 # Delete old thumbnails
1557 $this->purgeThumbnails();
1558 # Remove the old file from the CDN cache
1559 DeferredUpdates
::addUpdate(
1560 new CdnCacheUpdate( [ $this->getUrl() ] ),
1561 DeferredUpdates
::PRESEND
1564 # Update backlink pages pointing to this title if created
1565 LinksUpdate
::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' );
1568 $this->prerenderThumbnails();
1571 DeferredUpdates
::PRESEND
1575 # This is a new file, so update the image count
1576 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
1579 # Invalidate cache for all pages using this file
1580 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) );
1586 * Move or copy a file to its public location. If a file exists at the
1587 * destination, move it to an archive. Returns a Status object with
1588 * the archive name in the "value" member on success.
1590 * The archive name should be passed through to recordUpload for database
1593 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1594 * @param int $flags A bitwise combination of:
1595 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1596 * @param array $options Optional additional parameters
1597 * @return Status On success, the value member contains the
1598 * archive name, or an empty string if it was a new file.
1600 function publish( $src, $flags = 0, array $options = [] ) {
1601 return $this->publishTo( $src, $this->getRel(), $flags, $options );
1605 * Move or copy a file to a specified location. Returns a Status
1606 * object with the archive name in the "value" member on success.
1608 * The archive name should be passed through to recordUpload for database
1611 * @param string|FSFile $src Local filesystem path or virtual URL to the source image
1612 * @param string $dstRel Target relative path
1613 * @param int $flags A bitwise combination of:
1614 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1615 * @param array $options Optional additional parameters
1616 * @return Status On success, the value member contains the
1617 * archive name, or an empty string if it was a new file.
1619 function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) {
1620 $srcPath = ( $src instanceof FSFile
) ?
$src->getPath() : $src;
1622 $repo = $this->getRepo();
1623 if ( $repo->getReadOnlyReason() !== false ) {
1624 return $this->readOnlyFatalStatus();
1627 $this->lock(); // begin
1629 $archiveName = wfTimestamp( TS_MW
) . '!' . $this->getName();
1630 $archiveRel = 'archive/' . $this->getHashPath() . $archiveName;
1632 if ( $repo->hasSha1Storage() ) {
1633 $sha1 = $repo->isVirtualUrl( $srcPath )
1634 ?
$repo->getFileSha1( $srcPath )
1635 : FSFile
::getSha1Base36FromPath( $srcPath );
1636 /** @var FileBackendDBRepoWrapper $wrapperBackend */
1637 $wrapperBackend = $repo->getBackend();
1638 $dst = $wrapperBackend->getPathForSHA1( $sha1 );
1639 $status = $repo->quickImport( $src, $dst );
1640 if ( $flags & File
::DELETE_SOURCE
) {
1644 if ( $this->exists() ) {
1645 $status->value
= $archiveName;
1648 $flags = $flags & File
::DELETE_SOURCE ? LocalRepo
::DELETE_SOURCE
: 0;
1649 $status = $repo->publish( $srcPath, $dstRel, $archiveRel, $flags, $options );
1651 if ( $status->value
== 'new' ) {
1652 $status->value
= '';
1654 $status->value
= $archiveName;
1658 $this->unlock(); // done
1663 /** getLinksTo inherited */
1664 /** getExifData inherited */
1665 /** isLocal inherited */
1666 /** wasDeleted inherited */
1669 * Move file to the new title
1671 * Move current, old version and all thumbnails
1672 * to the new filename. Old file is deleted.
1674 * Cache purging is done; checks for validity
1675 * and logging are caller's responsibility
1677 * @param Title $target New file name
1680 function move( $target ) {
1681 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1682 return $this->readOnlyFatalStatus();
1685 wfDebugLog( 'imagemove', "Got request to move {$this->name} to " . $target->getText() );
1686 $batch = new LocalFileMoveBatch( $this, $target );
1688 $this->lock(); // begin
1689 $batch->addCurrent();
1690 $archiveNames = $batch->addOlds();
1691 $status = $batch->execute();
1692 $this->unlock(); // done
1694 wfDebugLog( 'imagemove', "Finished moving {$this->name}" );
1696 // Purge the source and target files...
1697 $oldTitleFile = wfLocalFile( $this->title
);
1698 $newTitleFile = wfLocalFile( $target );
1699 // To avoid slow purges in the transaction, move them outside...
1700 DeferredUpdates
::addUpdate(
1701 new AutoCommitUpdate(
1702 $this->getRepo()->getMasterDB(),
1704 function () use ( $oldTitleFile, $newTitleFile, $archiveNames ) {
1705 $oldTitleFile->purgeEverything();
1706 foreach ( $archiveNames as $archiveName ) {
1707 $oldTitleFile->purgeOldThumbnails( $archiveName );
1709 $newTitleFile->purgeEverything();
1712 DeferredUpdates
::PRESEND
1715 if ( $status->isOK() ) {
1716 // Now switch the object
1717 $this->title
= $target;
1718 // Force regeneration of the name and hashpath
1719 unset( $this->name
);
1720 unset( $this->hashPath
);
1727 * Delete all versions of the file.
1729 * Moves the files into an archive directory (or deletes them)
1730 * and removes the database rows.
1732 * Cache purging is done; logging is caller's responsibility.
1734 * @param string $reason
1735 * @param bool $suppress
1736 * @param User|null $user
1739 function delete( $reason, $suppress = false, $user = null ) {
1740 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1741 return $this->readOnlyFatalStatus();
1744 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1746 $this->lock(); // begin
1747 $batch->addCurrent();
1748 // Get old version relative paths
1749 $archiveNames = $batch->addOlds();
1750 $status = $batch->execute();
1751 $this->unlock(); // done
1753 if ( $status->isOK() ) {
1754 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => -1 ] ) );
1757 // To avoid slow purges in the transaction, move them outside...
1758 DeferredUpdates
::addUpdate(
1759 new AutoCommitUpdate(
1760 $this->getRepo()->getMasterDB(),
1762 function () use ( $archiveNames ) {
1763 $this->purgeEverything();
1764 foreach ( $archiveNames as $archiveName ) {
1765 $this->purgeOldThumbnails( $archiveName );
1769 DeferredUpdates
::PRESEND
1774 foreach ( $archiveNames as $archiveName ) {
1775 $purgeUrls[] = $this->getArchiveUrl( $archiveName );
1777 DeferredUpdates
::addUpdate( new CdnCacheUpdate( $purgeUrls ), DeferredUpdates
::PRESEND
);
1783 * Delete an old version of the file.
1785 * Moves the file into an archive directory (or deletes it)
1786 * and removes the database row.
1788 * Cache purging is done; logging is caller's responsibility.
1790 * @param string $archiveName
1791 * @param string $reason
1792 * @param bool $suppress
1793 * @param User|null $user
1794 * @throws MWException Exception on database or file store failure
1797 function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) {
1798 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1799 return $this->readOnlyFatalStatus();
1802 $batch = new LocalFileDeleteBatch( $this, $reason, $suppress, $user );
1804 $this->lock(); // begin
1805 $batch->addOld( $archiveName );
1806 $status = $batch->execute();
1807 $this->unlock(); // done
1809 $this->purgeOldThumbnails( $archiveName );
1810 if ( $status->isOK() ) {
1811 $this->purgeDescription();
1814 DeferredUpdates
::addUpdate(
1815 new CdnCacheUpdate( [ $this->getArchiveUrl( $archiveName ) ] ),
1816 DeferredUpdates
::PRESEND
1823 * Restore all or specified deleted revisions to the given file.
1824 * Permissions and logging are left to the caller.
1826 * May throw database exceptions on error.
1828 * @param array $versions Set of record ids of deleted items to restore,
1829 * or empty to restore all revisions.
1830 * @param bool $unsuppress
1833 function restore( $versions = [], $unsuppress = false ) {
1834 if ( $this->getRepo()->getReadOnlyReason() !== false ) {
1835 return $this->readOnlyFatalStatus();
1838 $batch = new LocalFileRestoreBatch( $this, $unsuppress );
1840 $this->lock(); // begin
1844 $batch->addIds( $versions );
1846 $status = $batch->execute();
1847 if ( $status->isGood() ) {
1848 $cleanupStatus = $batch->cleanup();
1849 $cleanupStatus->successCount
= 0;
1850 $cleanupStatus->failCount
= 0;
1851 $status->merge( $cleanupStatus );
1853 $this->unlock(); // done
1858 /** isMultipage inherited */
1859 /** pageCount inherited */
1860 /** scaleHeight inherited */
1861 /** getImageSize inherited */
1864 * Get the URL of the file description page.
1867 function getDescriptionUrl() {
1868 return $this->title
->getLocalURL();
1872 * Get the HTML text of the description page
1873 * This is not used by ImagePage for local files, since (among other things)
1874 * it skips the parser cache.
1876 * @param Language $lang What language to get description in (Optional)
1877 * @return bool|mixed
1879 function getDescriptionText( $lang = null ) {
1880 $revision = Revision
::newFromTitle( $this->title
, false, Revision
::READ_NORMAL
);
1884 $content = $revision->getContent();
1888 $pout = $content->getParserOutput( $this->title
, null, new ParserOptions( null, $lang ) );
1890 return $pout->getText();
1894 * @param int $audience
1898 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1900 if ( $audience == self
::FOR_PUBLIC
&& $this->isDeleted( self
::DELETED_COMMENT
) ) {
1902 } elseif ( $audience == self
::FOR_THIS_USER
1903 && !$this->userCan( self
::DELETED_COMMENT
, $user )
1907 return $this->description
;
1912 * @return bool|string
1914 function getTimestamp() {
1917 return $this->timestamp
;
1921 * @return bool|string
1923 public function getDescriptionTouched() {
1924 // The DB lookup might return false, e.g. if the file was just deleted, or the shared DB repo
1925 // itself gets it from elsewhere. To avoid repeating the DB lookups in such a case, we
1926 // need to differentiate between null (uninitialized) and false (failed to load).
1927 if ( $this->descriptionTouched
=== null ) {
1929 'page_namespace' => $this->title
->getNamespace(),
1930 'page_title' => $this->title
->getDBkey()
1932 $touched = $this->repo
->getReplicaDB()->selectField( 'page', 'page_touched', $cond, __METHOD__
);
1933 $this->descriptionTouched
= $touched ?
wfTimestamp( TS_MW
, $touched ) : false;
1936 return $this->descriptionTouched
;
1942 function getSha1() {
1944 // Initialise now if necessary
1945 if ( $this->sha1
== '' && $this->fileExists
) {
1946 $this->lock(); // begin
1948 $this->sha1
= $this->repo
->getFileSha1( $this->getPath() );
1949 if ( !wfReadOnly() && strval( $this->sha1
) != '' ) {
1950 $dbw = $this->repo
->getMasterDB();
1951 $dbw->update( 'image',
1952 [ 'img_sha1' => $this->sha1
],
1953 [ 'img_name' => $this->getName() ],
1955 $this->invalidateCache();
1958 $this->unlock(); // done
1965 * @return bool Whether to cache in RepoGroup (this avoids OOMs)
1967 function isCacheable() {
1970 // If extra data (metadata) was not loaded then it must have been large
1971 return $this->extraDataLoaded
1972 && strlen( serialize( $this->metadata
) ) <= self
::CACHE_FIELD_MAX_LEN
;
1979 public function acquireFileLock() {
1980 return $this->getRepo()->getBackend()->lockFiles(
1981 [ $this->getPath() ], LockManager
::LOCK_EX
, 10
1989 public function releaseFileLock() {
1990 return $this->getRepo()->getBackend()->unlockFiles(
1991 [ $this->getPath() ], LockManager
::LOCK_EX
1996 * Start an atomic DB section and lock the image for update
1997 * or increments a reference counter if the lock is already held
1999 * This method should not be used outside of LocalFile/LocalFile*Batch
2001 * @throws LocalFileLockError Throws an error if the lock was not acquired
2002 * @return bool Whether the file lock owns/spawned the DB transaction
2004 public function lock() {
2005 if ( !$this->locked
) {
2006 $logger = LoggerFactory
::getInstance( 'LocalFile' );
2008 $dbw = $this->repo
->getMasterDB();
2009 $makesTransaction = !$dbw->trxLevel();
2010 $dbw->startAtomic( self
::ATOMIC_SECTION_LOCK
);
2011 // T56736: use simple lock to handle when the file does not exist.
2012 // SELECT FOR UPDATE prevents changes, not other SELECTs with FOR UPDATE.
2013 // Also, that would cause contention on INSERT of similarly named rows.
2014 $status = $this->acquireFileLock(); // represents all versions of the file
2015 if ( !$status->isGood() ) {
2016 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2017 $logger->warning( "Failed to lock '{file}'", [ 'file' => $this->name
] );
2019 throw new LocalFileLockError( $status );
2021 // Release the lock *after* commit to avoid row-level contention.
2022 // Make sure it triggers on rollback() as well as commit() (T132921).
2023 $dbw->onTransactionResolution(
2024 function () use ( $logger ) {
2025 $status = $this->releaseFileLock();
2026 if ( !$status->isGood() ) {
2027 $logger->error( "Failed to unlock '{file}'", [ 'file' => $this->name
] );
2032 // Callers might care if the SELECT snapshot is safely fresh
2033 $this->lockedOwnTrx
= $makesTransaction;
2038 return $this->lockedOwnTrx
;
2042 * Decrement the lock reference count and end the atomic section if it reaches zero
2044 * This method should not be used outside of LocalFile/LocalFile*Batch
2046 * The commit and loc release will happen when no atomic sections are active, which
2047 * may happen immediately or at some point after calling this
2049 public function unlock() {
2050 if ( $this->locked
) {
2052 if ( !$this->locked
) {
2053 $dbw = $this->repo
->getMasterDB();
2054 $dbw->endAtomic( self
::ATOMIC_SECTION_LOCK
);
2055 $this->lockedOwnTrx
= false;
2063 protected function readOnlyFatalStatus() {
2064 return $this->getRepo()->newFatal( 'filereadonlyerror', $this->getName(),
2065 $this->getRepo()->getName(), $this->getRepo()->getReadOnlyReason() );
2069 * Clean up any dangling locks
2071 function __destruct() {
2074 } // LocalFile class
2076 # ------------------------------------------------------------------------------
2079 * Helper class for file deletion
2080 * @ingroup FileAbstraction
2082 class LocalFileDeleteBatch
{
2083 /** @var LocalFile */
2090 private $srcRels = [];
2093 private $archiveUrls = [];
2095 /** @var array Items to be processed in the deletion batch */
2096 private $deletionBatch;
2098 /** @var bool Whether to suppress all suppressable fields when deleting */
2109 * @param string $reason
2110 * @param bool $suppress
2111 * @param User|null $user
2113 function __construct( File
$file, $reason = '', $suppress = false, $user = null ) {
2114 $this->file
= $file;
2115 $this->reason
= $reason;
2116 $this->suppress
= $suppress;
2118 $this->user
= $user;
2121 $this->user
= $wgUser;
2123 $this->status
= $file->repo
->newGood();
2126 public function addCurrent() {
2127 $this->srcRels
['.'] = $this->file
->getRel();
2131 * @param string $oldName
2133 public function addOld( $oldName ) {
2134 $this->srcRels
[$oldName] = $this->file
->getArchiveRel( $oldName );
2135 $this->archiveUrls
[] = $this->file
->getArchiveUrl( $oldName );
2139 * Add the old versions of the image to the batch
2140 * @return array List of archive names from old versions
2142 public function addOlds() {
2145 $dbw = $this->file
->repo
->getMasterDB();
2146 $result = $dbw->select( 'oldimage',
2147 [ 'oi_archive_name' ],
2148 [ 'oi_name' => $this->file
->getName() ],
2152 foreach ( $result as $row ) {
2153 $this->addOld( $row->oi_archive_name
);
2154 $archiveNames[] = $row->oi_archive_name
;
2157 return $archiveNames;
2163 protected function getOldRels() {
2164 if ( !isset( $this->srcRels
['.'] ) ) {
2165 $oldRels =& $this->srcRels
;
2166 $deleteCurrent = false;
2168 $oldRels = $this->srcRels
;
2169 unset( $oldRels['.'] );
2170 $deleteCurrent = true;
2173 return [ $oldRels, $deleteCurrent ];
2179 protected function getHashes() {
2181 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2183 if ( $deleteCurrent ) {
2184 $hashes['.'] = $this->file
->getSha1();
2187 if ( count( $oldRels ) ) {
2188 $dbw = $this->file
->repo
->getMasterDB();
2189 $res = $dbw->select(
2191 [ 'oi_archive_name', 'oi_sha1' ],
2192 [ 'oi_archive_name' => array_keys( $oldRels ),
2193 'oi_name' => $this->file
->getName() ], // performance
2197 foreach ( $res as $row ) {
2198 if ( rtrim( $row->oi_sha1
, "\0" ) === '' ) {
2199 // Get the hash from the file
2200 $oldUrl = $this->file
->getArchiveVirtualUrl( $row->oi_archive_name
);
2201 $props = $this->file
->repo
->getFileProps( $oldUrl );
2203 if ( $props['fileExists'] ) {
2204 // Upgrade the oldimage row
2205 $dbw->update( 'oldimage',
2206 [ 'oi_sha1' => $props['sha1'] ],
2207 [ 'oi_name' => $this->file
->getName(), 'oi_archive_name' => $row->oi_archive_name
],
2209 $hashes[$row->oi_archive_name
] = $props['sha1'];
2211 $hashes[$row->oi_archive_name
] = false;
2214 $hashes[$row->oi_archive_name
] = $row->oi_sha1
;
2219 $missing = array_diff_key( $this->srcRels
, $hashes );
2221 foreach ( $missing as $name => $rel ) {
2222 $this->status
->error( 'filedelete-old-unregistered', $name );
2225 foreach ( $hashes as $name => $hash ) {
2227 $this->status
->error( 'filedelete-missing', $this->srcRels
[$name] );
2228 unset( $hashes[$name] );
2235 protected function doDBInserts() {
2237 $dbw = $this->file
->repo
->getMasterDB();
2238 $encTimestamp = $dbw->addQuotes( $dbw->timestamp( $now ) );
2239 $encUserId = $dbw->addQuotes( $this->user
->getId() );
2240 $encReason = $dbw->addQuotes( $this->reason
);
2241 $encGroup = $dbw->addQuotes( 'deleted' );
2242 $ext = $this->file
->getExtension();
2243 $dotExt = $ext === '' ?
'' : ".$ext";
2244 $encExt = $dbw->addQuotes( $dotExt );
2245 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2247 // Bitfields to further suppress the content
2248 if ( $this->suppress
) {
2249 $bitfield = Revision
::SUPPRESSED_ALL
;
2251 $bitfield = 'oi_deleted';
2254 if ( $deleteCurrent ) {
2259 'fa_storage_group' => $encGroup,
2260 'fa_storage_key' => $dbw->conditional(
2261 [ 'img_sha1' => '' ],
2262 $dbw->addQuotes( '' ),
2263 $dbw->buildConcat( [ "img_sha1", $encExt ] )
2265 'fa_deleted_user' => $encUserId,
2266 'fa_deleted_timestamp' => $encTimestamp,
2267 'fa_deleted_reason' => $encReason,
2268 'fa_deleted' => $this->suppress ?
$bitfield : 0,
2269 'fa_name' => 'img_name',
2270 'fa_archive_name' => 'NULL',
2271 'fa_size' => 'img_size',
2272 'fa_width' => 'img_width',
2273 'fa_height' => 'img_height',
2274 'fa_metadata' => 'img_metadata',
2275 'fa_bits' => 'img_bits',
2276 'fa_media_type' => 'img_media_type',
2277 'fa_major_mime' => 'img_major_mime',
2278 'fa_minor_mime' => 'img_minor_mime',
2279 'fa_description' => 'img_description',
2280 'fa_user' => 'img_user',
2281 'fa_user_text' => 'img_user_text',
2282 'fa_timestamp' => 'img_timestamp',
2283 'fa_sha1' => 'img_sha1'
2285 [ 'img_name' => $this->file
->getName() ],
2290 if ( count( $oldRels ) ) {
2291 $res = $dbw->select(
2293 OldLocalFile
::selectFields(),
2295 'oi_name' => $this->file
->getName(),
2296 'oi_archive_name' => array_keys( $oldRels )
2302 foreach ( $res as $row ) {
2304 // Deletion-specific fields
2305 'fa_storage_group' => 'deleted',
2306 'fa_storage_key' => ( $row->oi_sha1
=== '' )
2308 : "{$row->oi_sha1}{$dotExt}",
2309 'fa_deleted_user' => $this->user
->getId(),
2310 'fa_deleted_timestamp' => $dbw->timestamp( $now ),
2311 'fa_deleted_reason' => $this->reason
,
2312 // Counterpart fields
2313 'fa_deleted' => $this->suppress ?
$bitfield : $row->oi_deleted
,
2314 'fa_name' => $row->oi_name
,
2315 'fa_archive_name' => $row->oi_archive_name
,
2316 'fa_size' => $row->oi_size
,
2317 'fa_width' => $row->oi_width
,
2318 'fa_height' => $row->oi_height
,
2319 'fa_metadata' => $row->oi_metadata
,
2320 'fa_bits' => $row->oi_bits
,
2321 'fa_media_type' => $row->oi_media_type
,
2322 'fa_major_mime' => $row->oi_major_mime
,
2323 'fa_minor_mime' => $row->oi_minor_mime
,
2324 'fa_description' => $row->oi_description
,
2325 'fa_user' => $row->oi_user
,
2326 'fa_user_text' => $row->oi_user_text
,
2327 'fa_timestamp' => $row->oi_timestamp
,
2328 'fa_sha1' => $row->oi_sha1
2332 $dbw->insert( 'filearchive', $rowsInsert, __METHOD__
);
2336 function doDBDeletes() {
2337 $dbw = $this->file
->repo
->getMasterDB();
2338 list( $oldRels, $deleteCurrent ) = $this->getOldRels();
2340 if ( count( $oldRels ) ) {
2341 $dbw->delete( 'oldimage',
2343 'oi_name' => $this->file
->getName(),
2344 'oi_archive_name' => array_keys( $oldRels )
2348 if ( $deleteCurrent ) {
2349 $dbw->delete( 'image', [ 'img_name' => $this->file
->getName() ], __METHOD__
);
2354 * Run the transaction
2357 public function execute() {
2358 $repo = $this->file
->getRepo();
2359 $this->file
->lock();
2361 // Prepare deletion batch
2362 $hashes = $this->getHashes();
2363 $this->deletionBatch
= [];
2364 $ext = $this->file
->getExtension();
2365 $dotExt = $ext === '' ?
'' : ".$ext";
2367 foreach ( $this->srcRels
as $name => $srcRel ) {
2368 // Skip files that have no hash (e.g. missing DB record, or sha1 field and file source)
2369 if ( isset( $hashes[$name] ) ) {
2370 $hash = $hashes[$name];
2371 $key = $hash . $dotExt;
2372 $dstRel = $repo->getDeletedHashPath( $key ) . $key;
2373 $this->deletionBatch
[$name] = [ $srcRel, $dstRel ];
2377 if ( !$repo->hasSha1Storage() ) {
2378 // Removes non-existent file from the batch, so we don't get errors.
2379 // This also handles files in the 'deleted' zone deleted via revision deletion.
2380 $checkStatus = $this->removeNonexistentFiles( $this->deletionBatch
);
2381 if ( !$checkStatus->isGood() ) {
2382 $this->status
->merge( $checkStatus );
2383 return $this->status
;
2385 $this->deletionBatch
= $checkStatus->value
;
2387 // Execute the file deletion batch
2388 $status = $this->file
->repo
->deleteBatch( $this->deletionBatch
);
2389 if ( !$status->isGood() ) {
2390 $this->status
->merge( $status );
2394 if ( !$this->status
->isOK() ) {
2395 // Critical file deletion error; abort
2396 $this->file
->unlock();
2398 return $this->status
;
2401 // Copy the image/oldimage rows to filearchive
2402 $this->doDBInserts();
2403 // Delete image/oldimage rows
2404 $this->doDBDeletes();
2406 // Commit and return
2407 $this->file
->unlock();
2409 return $this->status
;
2413 * Removes non-existent files from a deletion batch.
2414 * @param array $batch
2417 protected function removeNonexistentFiles( $batch ) {
2418 $files = $newBatch = [];
2420 foreach ( $batch as $batchItem ) {
2421 list( $src, ) = $batchItem;
2422 $files[$src] = $this->file
->repo
->getVirtualUrl( 'public' ) . '/' . rawurlencode( $src );
2425 $result = $this->file
->repo
->fileExistsBatch( $files );
2426 if ( in_array( null, $result, true ) ) {
2427 return Status
::newFatal( 'backend-fail-internal',
2428 $this->file
->repo
->getBackend()->getName() );
2431 foreach ( $batch as $batchItem ) {
2432 if ( $result[$batchItem[0]] ) {
2433 $newBatch[] = $batchItem;
2437 return Status
::newGood( $newBatch );
2441 # ------------------------------------------------------------------------------
2444 * Helper class for file undeletion
2445 * @ingroup FileAbstraction
2447 class LocalFileRestoreBatch
{
2448 /** @var LocalFile */
2451 /** @var array List of file IDs to restore */
2452 private $cleanupBatch;
2454 /** @var array List of file IDs to restore */
2457 /** @var bool Add all revisions of the file */
2460 /** @var bool Whether to remove all settings for suppressed fields */
2461 private $unsuppress = false;
2465 * @param bool $unsuppress
2467 function __construct( File
$file, $unsuppress = false ) {
2468 $this->file
= $file;
2469 $this->cleanupBatch
= $this->ids
= [];
2471 $this->unsuppress
= $unsuppress;
2478 public function addId( $fa_id ) {
2479 $this->ids
[] = $fa_id;
2483 * Add a whole lot of files by ID
2486 public function addIds( $ids ) {
2487 $this->ids
= array_merge( $this->ids
, $ids );
2491 * Add all revisions of the file
2493 public function addAll() {
2498 * Run the transaction, except the cleanup batch.
2499 * The cleanup batch should be run in a separate transaction, because it locks different
2500 * rows and there's no need to keep the image row locked while it's acquiring those locks
2501 * The caller may have its own transaction open.
2502 * So we save the batch and let the caller call cleanup()
2505 public function execute() {
2506 /** @var Language */
2509 $repo = $this->file
->getRepo();
2510 if ( !$this->all
&& !$this->ids
) {
2512 return $repo->newGood();
2515 $lockOwnsTrx = $this->file
->lock();
2517 $dbw = $this->file
->repo
->getMasterDB();
2518 $status = $this->file
->repo
->newGood();
2520 $exists = (bool)$dbw->selectField( 'image', '1',
2521 [ 'img_name' => $this->file
->getName() ],
2523 // The lock() should already prevents changes, but this still may need
2524 // to bypass any transaction snapshot. However, if lock() started the
2525 // trx (which it probably did) then snapshot is post-lock and up-to-date.
2526 $lockOwnsTrx ?
[] : [ 'LOCK IN SHARE MODE' ]
2529 // Fetch all or selected archived revisions for the file,
2530 // sorted from the most recent to the oldest.
2531 $conditions = [ 'fa_name' => $this->file
->getName() ];
2533 if ( !$this->all
) {
2534 $conditions['fa_id'] = $this->ids
;
2537 $result = $dbw->select(
2539 ArchivedFile
::selectFields(),
2542 [ 'ORDER BY' => 'fa_timestamp DESC' ]
2548 $insertCurrent = false;
2553 foreach ( $result as $row ) {
2554 $idsPresent[] = $row->fa_id
;
2556 if ( $row->fa_name
!= $this->file
->getName() ) {
2557 $status->error( 'undelete-filename-mismatch', $wgLang->timeanddate( $row->fa_timestamp
) );
2558 $status->failCount++
;
2562 if ( $row->fa_storage_key
== '' ) {
2563 // Revision was missing pre-deletion
2564 $status->error( 'undelete-bad-store-key', $wgLang->timeanddate( $row->fa_timestamp
) );
2565 $status->failCount++
;
2569 $deletedRel = $repo->getDeletedHashPath( $row->fa_storage_key
) .
2570 $row->fa_storage_key
;
2571 $deletedUrl = $repo->getVirtualUrl() . '/deleted/' . $deletedRel;
2573 if ( isset( $row->fa_sha1
) ) {
2574 $sha1 = $row->fa_sha1
;
2576 // old row, populate from key
2577 $sha1 = LocalRepo
::getHashFromKey( $row->fa_storage_key
);
2581 if ( strlen( $sha1 ) == 32 && $sha1[0] == '0' ) {
2582 $sha1 = substr( $sha1, 1 );
2585 if ( is_null( $row->fa_major_mime
) ||
$row->fa_major_mime
== 'unknown'
2586 ||
is_null( $row->fa_minor_mime
) ||
$row->fa_minor_mime
== 'unknown'
2587 ||
is_null( $row->fa_media_type
) ||
$row->fa_media_type
== 'UNKNOWN'
2588 ||
is_null( $row->fa_metadata
)
2590 // Refresh our metadata
2591 // Required for a new current revision; nice for older ones too. :)
2592 $props = RepoGroup
::singleton()->getFileProps( $deletedUrl );
2595 'minor_mime' => $row->fa_minor_mime
,
2596 'major_mime' => $row->fa_major_mime
,
2597 'media_type' => $row->fa_media_type
,
2598 'metadata' => $row->fa_metadata
2602 if ( $first && !$exists ) {
2603 // This revision will be published as the new current version
2604 $destRel = $this->file
->getRel();
2606 'img_name' => $row->fa_name
,
2607 'img_size' => $row->fa_size
,
2608 'img_width' => $row->fa_width
,
2609 'img_height' => $row->fa_height
,
2610 'img_metadata' => $props['metadata'],
2611 'img_bits' => $row->fa_bits
,
2612 'img_media_type' => $props['media_type'],
2613 'img_major_mime' => $props['major_mime'],
2614 'img_minor_mime' => $props['minor_mime'],
2615 'img_description' => $row->fa_description
,
2616 'img_user' => $row->fa_user
,
2617 'img_user_text' => $row->fa_user_text
,
2618 'img_timestamp' => $row->fa_timestamp
,
2622 // The live (current) version cannot be hidden!
2623 if ( !$this->unsuppress
&& $row->fa_deleted
) {
2624 $status->fatal( 'undeleterevdel' );
2625 $this->file
->unlock();
2629 $archiveName = $row->fa_archive_name
;
2631 if ( $archiveName == '' ) {
2632 // This was originally a current version; we
2633 // have to devise a new archive name for it.
2634 // Format is <timestamp of archiving>!<name>
2635 $timestamp = wfTimestamp( TS_UNIX
, $row->fa_deleted_timestamp
);
2638 $archiveName = wfTimestamp( TS_MW
, $timestamp ) . '!' . $row->fa_name
;
2640 } while ( isset( $archiveNames[$archiveName] ) );
2643 $archiveNames[$archiveName] = true;
2644 $destRel = $this->file
->getArchiveRel( $archiveName );
2646 'oi_name' => $row->fa_name
,
2647 'oi_archive_name' => $archiveName,
2648 'oi_size' => $row->fa_size
,
2649 'oi_width' => $row->fa_width
,
2650 'oi_height' => $row->fa_height
,
2651 'oi_bits' => $row->fa_bits
,
2652 'oi_description' => $row->fa_description
,
2653 'oi_user' => $row->fa_user
,
2654 'oi_user_text' => $row->fa_user_text
,
2655 'oi_timestamp' => $row->fa_timestamp
,
2656 'oi_metadata' => $props['metadata'],
2657 'oi_media_type' => $props['media_type'],
2658 'oi_major_mime' => $props['major_mime'],
2659 'oi_minor_mime' => $props['minor_mime'],
2660 'oi_deleted' => $this->unsuppress ?
0 : $row->fa_deleted
,
2661 'oi_sha1' => $sha1 ];
2664 $deleteIds[] = $row->fa_id
;
2666 if ( !$this->unsuppress
&& $row->fa_deleted
& File
::DELETED_FILE
) {
2667 // private files can stay where they are
2668 $status->successCount++
;
2670 $storeBatch[] = [ $deletedUrl, 'public', $destRel ];
2671 $this->cleanupBatch
[] = $row->fa_storage_key
;
2679 // Add a warning to the status object for missing IDs
2680 $missingIds = array_diff( $this->ids
, $idsPresent );
2682 foreach ( $missingIds as $id ) {
2683 $status->error( 'undelete-missing-filearchive', $id );
2686 if ( !$repo->hasSha1Storage() ) {
2687 // Remove missing files from batch, so we don't get errors when undeleting them
2688 $checkStatus = $this->removeNonexistentFiles( $storeBatch );
2689 if ( !$checkStatus->isGood() ) {
2690 $status->merge( $checkStatus );
2693 $storeBatch = $checkStatus->value
;
2695 // Run the store batch
2696 // Use the OVERWRITE_SAME flag to smooth over a common error
2697 $storeStatus = $this->file
->repo
->storeBatch( $storeBatch, FileRepo
::OVERWRITE_SAME
);
2698 $status->merge( $storeStatus );
2700 if ( !$status->isGood() ) {
2701 // Even if some files could be copied, fail entirely as that is the
2702 // easiest thing to do without data loss
2703 $this->cleanupFailedBatch( $storeStatus, $storeBatch );
2704 $status->setOK( false );
2705 $this->file
->unlock();
2711 // Run the DB updates
2712 // Because we have locked the image row, key conflicts should be rare.
2713 // If they do occur, we can roll back the transaction at this time with
2714 // no data loss, but leaving unregistered files scattered throughout the
2716 // This is not ideal, which is why it's important to lock the image row.
2717 if ( $insertCurrent ) {
2718 $dbw->insert( 'image', $insertCurrent, __METHOD__
);
2721 if ( $insertBatch ) {
2722 $dbw->insert( 'oldimage', $insertBatch, __METHOD__
);
2726 $dbw->delete( 'filearchive',
2727 [ 'fa_id' => $deleteIds ],
2731 // If store batch is empty (all files are missing), deletion is to be considered successful
2732 if ( $status->successCount
> 0 ||
!$storeBatch ||
$repo->hasSha1Storage() ) {
2734 wfDebug( __METHOD__
. " restored {$status->successCount} items, creating a new current\n" );
2736 DeferredUpdates
::addUpdate( SiteStatsUpdate
::factory( [ 'images' => 1 ] ) );
2738 $this->file
->purgeEverything();
2740 wfDebug( __METHOD__
. " restored {$status->successCount} as archived versions\n" );
2741 $this->file
->purgeDescription();
2745 $this->file
->unlock();
2751 * Removes non-existent files from a store batch.
2752 * @param array $triplets
2755 protected function removeNonexistentFiles( $triplets ) {
2756 $files = $filteredTriplets = [];
2757 foreach ( $triplets as $file ) {
2758 $files[$file[0]] = $file[0];
2761 $result = $this->file
->repo
->fileExistsBatch( $files );
2762 if ( in_array( null, $result, true ) ) {
2763 return Status
::newFatal( 'backend-fail-internal',
2764 $this->file
->repo
->getBackend()->getName() );
2767 foreach ( $triplets as $file ) {
2768 if ( $result[$file[0]] ) {
2769 $filteredTriplets[] = $file;
2773 return Status
::newGood( $filteredTriplets );
2777 * Removes non-existent files from a cleanup batch.
2778 * @param array $batch
2781 protected function removeNonexistentFromCleanup( $batch ) {
2782 $files = $newBatch = [];
2783 $repo = $this->file
->repo
;
2785 foreach ( $batch as $file ) {
2786 $files[$file] = $repo->getVirtualUrl( 'deleted' ) . '/' .
2787 rawurlencode( $repo->getDeletedHashPath( $file ) . $file );
2790 $result = $repo->fileExistsBatch( $files );
2792 foreach ( $batch as $file ) {
2793 if ( $result[$file] ) {
2794 $newBatch[] = $file;
2802 * Delete unused files in the deleted zone.
2803 * This should be called from outside the transaction in which execute() was called.
2806 public function cleanup() {
2807 if ( !$this->cleanupBatch
) {
2808 return $this->file
->repo
->newGood();
2811 $this->cleanupBatch
= $this->removeNonexistentFromCleanup( $this->cleanupBatch
);
2813 $status = $this->file
->repo
->cleanupDeletedBatch( $this->cleanupBatch
);
2819 * Cleanup a failed batch. The batch was only partially successful, so
2820 * rollback by removing all items that were succesfully copied.
2822 * @param Status $storeStatus
2823 * @param array $storeBatch
2825 protected function cleanupFailedBatch( $storeStatus, $storeBatch ) {
2828 foreach ( $storeStatus->success
as $i => $success ) {
2829 // Check if this item of the batch was successfully copied
2831 // Item was successfully copied and needs to be removed again
2832 // Extract ($dstZone, $dstRel) from the batch
2833 $cleanupBatch[] = [ $storeBatch[$i][1], $storeBatch[$i][2] ];
2836 $this->file
->repo
->cleanupBatch( $cleanupBatch );
2840 # ------------------------------------------------------------------------------
2843 * Helper class for file movement
2844 * @ingroup FileAbstraction
2846 class LocalFileMoveBatch
{
2847 /** @var LocalFile */
2857 protected $oldCount;
2861 /** @var IDatabase */
2866 * @param Title $target
2868 function __construct( File
$file, Title
$target ) {
2869 $this->file
= $file;
2870 $this->target
= $target;
2871 $this->oldHash
= $this->file
->repo
->getHashPath( $this->file
->getName() );
2872 $this->newHash
= $this->file
->repo
->getHashPath( $this->target
->getDBkey() );
2873 $this->oldName
= $this->file
->getName();
2874 $this->newName
= $this->file
->repo
->getNameFromTitle( $this->target
);
2875 $this->oldRel
= $this->oldHash
. $this->oldName
;
2876 $this->newRel
= $this->newHash
. $this->newName
;
2877 $this->db
= $file->getRepo()->getMasterDB();
2881 * Add the current image to the batch
2883 public function addCurrent() {
2884 $this->cur
= [ $this->oldRel
, $this->newRel
];
2888 * Add the old versions of the image to the batch
2889 * @return array List of archive names from old versions
2891 public function addOlds() {
2892 $archiveBase = 'archive';
2894 $this->oldCount
= 0;
2897 $result = $this->db
->select( 'oldimage',
2898 [ 'oi_archive_name', 'oi_deleted' ],
2899 [ 'oi_name' => $this->oldName
],
2901 [ 'LOCK IN SHARE MODE' ] // ignore snapshot
2904 foreach ( $result as $row ) {
2905 $archiveNames[] = $row->oi_archive_name
;
2906 $oldName = $row->oi_archive_name
;
2907 $bits = explode( '!', $oldName, 2 );
2909 if ( count( $bits ) != 2 ) {
2910 wfDebug( "Old file name missing !: '$oldName' \n" );
2914 list( $timestamp, $filename ) = $bits;
2916 if ( $this->oldName
!= $filename ) {
2917 wfDebug( "Old file name doesn't match: '$oldName' \n" );
2923 // Do we want to add those to oldCount?
2924 if ( $row->oi_deleted
& File
::DELETED_FILE
) {
2929 "{$archiveBase}/{$this->oldHash}{$oldName}",
2930 "{$archiveBase}/{$this->newHash}{$timestamp}!{$this->newName}"
2934 return $archiveNames;
2941 public function execute() {
2942 $repo = $this->file
->repo
;
2943 $status = $repo->newGood();
2944 $destFile = wfLocalFile( $this->target
);
2946 $this->file
->lock(); // begin
2947 $destFile->lock(); // quickly fail if destination is not available
2949 $triplets = $this->getMoveTriplets();
2950 $checkStatus = $this->removeNonexistentFiles( $triplets );
2951 if ( !$checkStatus->isGood() ) {
2952 $destFile->unlock();
2953 $this->file
->unlock();
2954 $status->merge( $checkStatus ); // couldn't talk to file backend
2957 $triplets = $checkStatus->value
;
2959 // Verify the file versions metadata in the DB.
2960 $statusDb = $this->verifyDBUpdates();
2961 if ( !$statusDb->isGood() ) {
2962 $destFile->unlock();
2963 $this->file
->unlock();
2964 $statusDb->setOK( false );
2969 if ( !$repo->hasSha1Storage() ) {
2970 // Copy the files into their new location.
2971 // If a prior process fataled copying or cleaning up files we tolerate any
2972 // of the existing files if they are identical to the ones being stored.
2973 $statusMove = $repo->storeBatch( $triplets, FileRepo
::OVERWRITE_SAME
);
2974 wfDebugLog( 'imagemove', "Moved files for {$this->file->getName()}: " .
2975 "{$statusMove->successCount} successes, {$statusMove->failCount} failures" );
2976 if ( !$statusMove->isGood() ) {
2977 // Delete any files copied over (while the destination is still locked)
2978 $this->cleanupTarget( $triplets );
2979 $destFile->unlock();
2980 $this->file
->unlock();
2981 wfDebugLog( 'imagemove', "Error in moving files: "
2982 . $statusMove->getWikiText( false, false, 'en' ) );
2983 $statusMove->setOK( false );
2987 $status->merge( $statusMove );
2990 // Rename the file versions metadata in the DB.
2991 $this->doDBUpdates();
2993 wfDebugLog( 'imagemove', "Renamed {$this->file->getName()} in database: " .
2994 "{$statusDb->successCount} successes, {$statusDb->failCount} failures" );
2996 $destFile->unlock();
2997 $this->file
->unlock(); // done
2999 // Everything went ok, remove the source files
3000 $this->cleanupSource( $triplets );
3002 $status->merge( $statusDb );
3008 * Verify the database updates and return a new Status indicating how
3009 * many rows would be updated.
3013 protected function verifyDBUpdates() {
3014 $repo = $this->file
->repo
;
3015 $status = $repo->newGood();
3018 $hasCurrent = $dbw->selectField(
3021 [ 'img_name' => $this->oldName
],
3025 $oldRowCount = $dbw->selectField(
3028 [ 'oi_name' => $this->oldName
],
3033 if ( $hasCurrent ) {
3034 $status->successCount++
;
3036 $status->failCount++
;
3038 $status->successCount +
= $oldRowCount;
3039 // T36934: oldCount is based on files that actually exist.
3040 // There may be more DB rows than such files, in which case $affected
3041 // can be greater than $total. We use max() to avoid negatives here.
3042 $status->failCount +
= max( 0, $this->oldCount
- $oldRowCount );
3043 if ( $status->failCount
) {
3044 $status->error( 'imageinvalidfilename' );
3051 * Do the database updates and return a new Status indicating how
3052 * many rows where updated.
3054 protected function doDBUpdates() {
3057 // Update current image
3060 [ 'img_name' => $this->newName
],
3061 [ 'img_name' => $this->oldName
],
3064 // Update old images
3068 'oi_name' => $this->newName
,
3069 'oi_archive_name = ' . $dbw->strreplace( 'oi_archive_name',
3070 $dbw->addQuotes( $this->oldName
), $dbw->addQuotes( $this->newName
) ),
3072 [ 'oi_name' => $this->oldName
],
3078 * Generate triplets for FileRepo::storeBatch().
3081 protected function getMoveTriplets() {
3082 $moves = array_merge( [ $this->cur
], $this->olds
);
3083 $triplets = []; // The format is: (srcUrl, destZone, destUrl)
3085 foreach ( $moves as $move ) {
3086 // $move: (oldRelativePath, newRelativePath)
3087 $srcUrl = $this->file
->repo
->getVirtualUrl() . '/public/' . rawurlencode( $move[0] );
3088 $triplets[] = [ $srcUrl, 'public', $move[1] ];
3091 "Generated move triplet for {$this->file->getName()}: {$srcUrl} :: public :: {$move[1]}"
3099 * Removes non-existent files from move batch.
3100 * @param array $triplets
3103 protected function removeNonexistentFiles( $triplets ) {
3106 foreach ( $triplets as $file ) {
3107 $files[$file[0]] = $file[0];
3110 $result = $this->file
->repo
->fileExistsBatch( $files );
3111 if ( in_array( null, $result, true ) ) {
3112 return Status
::newFatal( 'backend-fail-internal',
3113 $this->file
->repo
->getBackend()->getName() );
3116 $filteredTriplets = [];
3117 foreach ( $triplets as $file ) {
3118 if ( $result[$file[0]] ) {
3119 $filteredTriplets[] = $file;
3121 wfDebugLog( 'imagemove', "File {$file[0]} does not exist" );
3125 return Status
::newGood( $filteredTriplets );
3129 * Cleanup a partially moved array of triplets by deleting the target
3130 * files. Called if something went wrong half way.
3131 * @param array $triplets
3133 protected function cleanupTarget( $triplets ) {
3134 // Create dest pairs from the triplets
3136 foreach ( $triplets as $triplet ) {
3137 // $triplet: (old source virtual URL, dst zone, dest rel)
3138 $pairs[] = [ $triplet[1], $triplet[2] ];
3141 $this->file
->repo
->cleanupBatch( $pairs );
3145 * Cleanup a fully moved array of triplets by deleting the source files.
3146 * Called at the end of the move process if everything else went ok.
3147 * @param array $triplets
3149 protected function cleanupSource( $triplets ) {
3150 // Create source file names from the triplets
3152 foreach ( $triplets as $triplet ) {
3153 $files[] = $triplet[0];
3156 $this->file
->repo
->cleanupBatch( $files );
3160 class LocalFileLockError
extends ErrorPageError
{
3161 public function __construct( Status
$status ) {
3162 parent
::__construct(
3164 $status->getMessage()
3168 public function report() {
3170 $wgOut->setStatusCode( 429 );